package com.twan.base.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.alipay.sdk.app.PayTask;
import com.lxj.xpopup.animator.PopupAnimator;
import com.lxj.xpopup.core.CenterPopupView;
import com.twan.base.R;
import com.twan.base.api.Api;
import com.twan.base.entity.AliPayBean;
import com.twan.base.entity.MyWaterBean;
import com.twan.base.entity.PayResult;
import com.twan.base.network.ZyCallBack;
import com.twan.base.util.SPUtils;
import com.twan.base.util.ToastUtil;

import java.util.Map;

/**
 * @author Twan
 * @date 2019/4/19
 */
public class TenementFeePop extends CenterPopupView {
    //自定义弹窗本质是一个自定义View，但是只需重写这个构造，其他的不用重写
    String mType="",mId="";
    Activity mContext;
    IPayListener payListener;
    public TenementFeePop(@NonNull Activity context, String type,String id,IPayListener listener) {
        super(context);
        mContext = context;
        mType = type;
        mId = id;
        payListener = listener;
    }
    // 返回自定义弹窗的布局
    @Override
    protected int getImplLayoutId() {
        return R.layout.pop_tenement_fee;
    }
    // 执行初始化操作，比如：findView，设置点击，或者任何你弹窗内的业务逻辑
    @Override
    protected void onCreate() {
        super.onCreate();
        final CheckBox chb_wx = findViewById(R.id.chb_wx);
        final CheckBox chb_zfb = findViewById(R.id.chb_zfb);
        final Button btn_pay = findViewById(R.id.btn_pay);
        chb_zfb.setClickable(false);
        chb_wx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                chb_zfb.setChecked(!isChecked);
            }
        });
        chb_zfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                chb_wx.setChecked(true);//固定勾选
            }
        });
        btn_pay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getPayUrl();
            }
        });
    }
    // 设置自定义动画器，看需要而定
    @Override
    protected PopupAnimator getPopupAnimator() {
        return super.getPopupAnimator();
    }

    private void getPayUrl(){
        Api.getApiService().addZf(mType,mId,"2").enqueue(new ZyCallBack<AliPayBean>() {
            @Override
            public void doSuccess() {
                AliPayBean bean = mData;
                if (bean != null){
                    String zfUrl = bean.getParms();
                    alipay(zfUrl);
                }
            }
        });
    }

    private void alipay(final String payurl){
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mContext);
                Map<String, String> result = alipay.payV2(payurl, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.success("支付成功");
                        TenementFeePop.this.dismiss();
                        if (payListener != null){
                            payListener.onsuccess();
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtil.error("支付失败:" + payResult.getMemo());
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    public interface IPayListener {
        void onsuccess();
    }
}
